package org.test4j.mock.processor.filer;

import org.test4j.mock.Mocks;

import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 在 Processor中直接获取嵌套的注解, 会报 MirroredTypeException 异常
 *
 * @author darui.wu
 */
public class MocksAttribute {
    public static final String ATTR_VALUE = "value()";

    /**
     * 返回class列表
     *
     * @param entity
     * @return
     */
    public static List<String> getClasses(TypeElement entity) {
        AnnotationMirror mirror = getMocksMirror(entity);
        if (mirror == null) {
            return Collections.emptyList();
        }

        Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = mirror.getElementValues();
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementValues.entrySet()) {
            ExecutableElement method = entry.getKey();
            AnnotationValue value = entry.getValue();
            if (!method.toString().contains(ATTR_VALUE)) {
                continue;
            }
            List<AnnotationValue> list = (List) value.getValue();
            List<String> values = new ArrayList<>(list.size());
            for (AnnotationValue item : list) {
                values.add(item.getValue().toString());
            }
            return values;
        }
        return Collections.emptyList();
    }

    private static AnnotationMirror getMocksMirror(TypeElement element) {
        List<? extends AnnotationMirror> annotations = element.getAnnotationMirrors();
        for (AnnotationMirror annotation : annotations) {
            if (annotation.getAnnotationType().toString().contains(Mocks.class.getSimpleName())) {
                return annotation;
            }
        }
        return null;
    }
}